<template>
  <div class="app-container">
    <div class="top-section-container">
      <div class="content-header">
        <h1>会员管理/<small>会员档案</small></h1>
        <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>会员管理</el-breadcrumb-item>
          <el-breadcrumb-item>会员档案</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="bottom-section-container">
      <div class="search-bar filter-container">
        <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            clearable
            style="width: 200px; margin-right: 10px;"
        ></el-input>
        <el-input
            v-model="searchForm.phoneNumber"
            placeholder="请输入手机号"
            clearable
            style="width: 200px; margin-right: 10px;"
        ></el-input>
        <el-select
            v-model="searchForm.sex"
            placeholder="请选择性别"
            clearable
            style="width: 120px; margin-right: 10px;"
        >
          <el-option label="不限" value=""></el-option>
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
          <el-option label="未知" value="0"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增会员</el-button>
      </div>

      <el-table :data="memberList" style="width: 100%; margin-top: 20px;" border stripe>
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="fileNumber" label="档案号" width="120" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120" align="center"></el-table-column>
        <el-table-column
            prop="sex"
            label="性别"
            width="80"
            :formatter="sexFormatter"
            align="center"
        ></el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="180" align="center"></el-table-column>
        <el-table-column prop="phoneNumber" label="手机号" width="150" align="center"></el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="120" align="center"></el-table-column>
        <el-table-column prop="regTime" label="注册时间" width="180" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip></el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          background
          style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @close="handleDialogClose"
    >
      <el-form :model="memberForm" :rules="memberFormRules" ref="memberFormRef" label-width="90px">
        <el-form-item label="档案号" prop="fileNumber">
          <el-input v-model="memberForm.fileNumber"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="memberForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="memberForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
            <el-radio label="0">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="memberForm.idCard"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="memberForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
              v-model="memberForm.birthday"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="memberForm.email"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="memberForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMemberForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 假设这里引入了用于后端请求的 axios 或其他库
// import axios from 'axios';

// 搜索表单数据
const searchForm = reactive({
  name: '',
  phoneNumber: '',
  sex: '',
});

// 会员列表数据
const memberList = ref([]);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const memberForm = reactive({
  id: null,
  fileNumber: '',
  name: '',
  sex: '1', // 默认男
  idCard: '',
  phoneNumber: '',
  email: '',
  birthday: '',
  remark: '',
});
const memberFormRef = ref(null); // 表单引用，用于表单验证

// 表单验证规则
const memberFormRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  fileNumber: [{ required: true, message: '请输入档案号', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证格式不正确', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
});

// 性别格式化函数
const sexFormatter = (row, column, cellValue) => {
  switch (cellValue) {
    case '1':
      return '男';
    case '2':
      return '女';
    case '0':
      return '未知';
    default:
      return '未知';
  }
};

// 获取会员列表数据（模拟）
const fetchMemberList = () => {
  // 实际项目中，这里会发送 Axios 请求到后端 API
  console.log('Fetching member list with:', {
    ...searchForm,
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
  });

  // 模拟数据
  const mockData = Array.from({ length: 50 }).map((_, i) => ({
    id: i + 1,
    fileNumber: `M${String(i + 1).padStart(4, '0')}`,
    name: `会员${i + 1}`,
    sex: (i % 3).toString(), // 0, 1, 2 循环
    idCard: `44000019900101${String(1000 + i).padStart(4, '0')}`,
    phoneNumber: `13${String(5000000000 + i).padStart(9, '0')}`,
    regTime: `2023-01-${String(1 + i % 30).padStart(2, '0')} 10:00:00`,
    birthday: `1990-01-${String(1 + i % 30).padStart(2, '0')}`,
    email: `member${i+1}@example.com`,
    remark: `这是会员${i + 1}的备注信息`,
  }));

  // 根据搜索条件过滤模拟数据
  let filteredData = mockData.filter(member => {
    const nameMatch = searchForm.name ? member.name.includes(searchForm.name) : true;
    const phoneMatch = searchForm.phoneNumber ? member.phoneNumber.includes(searchForm.phoneNumber) : true;
    const sexMatch = searchForm.sex ? member.sex === searchForm.sex : true;
    return nameMatch && phoneMatch && sexMatch;
  });

  pagination.total = filteredData.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  memberList.value = filteredData.slice(start, end);
};

// 搜索按钮点击
const handleSearch = () => {
  pagination.currentPage = 1; // 搜索时重置回第一页
  fetchMemberList();
};

// 重置按钮点击
const handleReset = () => {
  searchForm.name = '';
  searchForm.phoneNumber = '';
  searchForm.sex = '';
  pagination.currentPage = 1;
  fetchMemberList();
};

// 新增会员
const handleAdd = () => {
  dialogTitle.value = '新增会员';
  // 重置表单
  Object.assign(memberForm, {
    id: null,
    fileNumber: '',
    name: '',
    sex: '1',
    idCard: '',
    phoneNumber: '',
    email: '',
    birthday: '',
    remark: '',
  });
  dialogVisible.value = true;
};

// 编辑会员
const handleEdit = (row) => {
  dialogTitle.value = '编辑会员';
  // 填充表单数据，确保深拷贝避免直接修改表格数据
  Object.assign(memberForm, { ...row });
  // Element Plus 的 date-picker 如果绑定的是字符串，需要确保格式正确
  if (memberForm.birthday && typeof memberForm.birthday === 'string') {
    memberForm.birthday = new Date(memberForm.birthday); // 转换为 Date 对象
  }
  dialogVisible.value = true;
};

// 删除会员
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除会员 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 实际项目中发送删除请求
    // axios.delete(`/member/delete/${row.id}`).then(() => {
    ElMessage.success('删除成功！');
    fetchMemberList(); // 重新加载数据
    // }).catch(error => {
    //   ElMessage.error('删除失败！');
    //   console.error(error);
    // });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 提交新增/编辑表单
const submitMemberForm = () => {
  memberFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中发送请求
      const apiEndpoint = memberForm.id ? '/member/update' : '/member/add';
      console.log('Submitting member form:', memberForm);

      // axios.post(apiEndpoint, memberForm).then(() => {
      ElMessage.success(memberForm.id ? '更新成功！' : '新增成功！');
      dialogVisible.value = false;
      fetchMemberList(); // 重新加载数据
      // }).catch(error => {
      //   ElMessage.error('操作失败！');
      //   console.error(error);
      // });
    } else {
      ElMessage.error('请检查表单填写是否完整正确！');
      return false;
    }
  });
};

// 弹窗关闭时清空表单校验状态
const handleDialogClose = () => {
  if (memberFormRef.value) { // 确保ref已赋值
    memberFormRef.value.resetFields();
  }
};

// 分页每页数量改变
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchMemberList();
};

// 分页当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  fetchMemberList();
};

// 组件挂载时加载数据
onMounted(() => {
  fetchMemberList();
});
</script>

<style scoped>
/* 容器基本样式，模仿 app-container */
.app-container {
  padding: 0; /* 外部容器不设 padding，让内部 section 控制 */
  box-sizing: border-box;
}

/* 顶部区域样式 */
.top-section-container {
  background-color: #f9f9f9; /* 浅灰色背景 */
  padding: 1.25rem 1.25rem 0.625rem; /* 内边距 */
  border-bottom: 3px solid #409EFF; /* 蓝色底部边框 */
  margin-bottom: 1.25rem; /* 与下方内容区域的间距 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 底部阴影 */
}

/* 底部内容区域样式 */
.bottom-section-container {
  background-color: #ffffff; /* 白色背景 */
  padding: 1.25rem; /* 内边距 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 阴影 */
  border-radius: 0.25rem; /* 圆角 */
  margin: 0 1.25rem 1.25rem 1.25rem; /* 左右和底部留白 */
}

/* 现有样式调整 */
.content-header {
  padding-bottom: 0.625rem; /* 保持面包屑和标题的底部间距 */
}

/* 搜索/过滤容器，去除之前可能添加的边框或阴影 */
.search-bar.filter-container {
  padding: 0; /* 在 bottom-section-container 中，filter-container 不再需要额外的 padding */
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /* 移除之前为模拟分割线而添加的样式 */
  border-bottom: none;
  padding-bottom: 0;
  box-shadow: none;
}

/* 确保表格操作列按钮间距 */
.el-table .el-button + .el-button {
  margin-left: 5px;
}

.dialog-footer {
  text-align: right;
  margin-top: 1.25rem;
}
</style>